from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from rankings.models import Ranking, Persona
from django.shortcuts import render, get_object_or_404

def index(request):
	lista_rankings = Ranking.objects.all()
	context = {'lista_rankings' : lista_rankings}
	return render(request, 'rankings/index.html', context)

def detail(request, ranking_id):
	ranking = get_object_or_404(Ranking, pk=ranking_id)
	return render(request, 'rankings/detail.html', {'ranking' : ranking})

def vote(request, ranking_id):
	r = get_object_or_404(Ranking, pk=ranking_id)
	try:
		selected_persona = r.persona_set.get(pk=request.POST['persona'])
	except(KeyError, Persona.DoesNotExist):
		return render(request, 'rankings/detail.html', {
				'ranking' : r,
				'error_message' : "No has seleccionado un voto.",
			})
	else:
		selected_persona.votes += 1
		selected_persona.save()
		#Cuando la peticion post es correcta devolvemos HttpResponseRedirect
		return HttpResponseRedirect(reverse('rankings:results', args=(r.id,)))

def results(request, ranking_id):
	ranking = get_object_or_404(Ranking,pk=ranking_id)
	return render(request, 'rankings/results.html', {'ranking': ranking})
